<script setup>
import * as echarts from 'echarts/core'
import {
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
} from 'echarts/components'
import { BarChart, LineChart, PieChart } from 'echarts/charts'
import { UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
import { onMounted, ref, computed, watch } from 'vue'
import { propTypes } from '@/utils/propTypes'
import { getTableList } from '@/api/basic'
import { getOptions } from '@/utils/echarts'

echarts.use([
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  BarChart,
  LineChart,
  PieChart,
  CanvasRenderer,
  UniversalTransition
])

const props = defineProps({
  config: propTypes.object.def({})
})
const pageTitle = computed(() => {
  return props.config?.title
})
const fields = computed(() => {
  return props.config?.meta?.fields || []
})
const source = computed(() => {
  return props.config?.meta?.source
})
const echartConfig = computed(() => {
  return props.config?.meta?.echarts
})

const domRef = ref()
// 数据列表
const dataList = ref([])
// echart配置项
const echartOptions = ref({})
// echarts实例
let echartInstance = null

const getList = async (source) => {
  if (source) {
    const params = { page: 1, size: 20, as_dict: true, conditions: {}, source }
    const { data } = await getTableList(params)
    dataList.value = data
  }
  console.log(echartConfig.value, dataList.value, fields.value)
  echartOptions.value = getOptions(echartConfig.value, dataList.value, fields.value)
  console.log(echartOptions.value)
}
getList(source.value)

// 初始化echarts
const initEcharts = () => {
  var chartDom = domRef.value
  echartInstance = echarts.init(chartDom)
  if (echartOptions.value && echartOptions.value.series) {
    echartInstance.setOption(echartOptions.value)
  }
}

onMounted(async () => {
  initEcharts()
})

watch(
  () => {
    return [!!echartInstance, !!(echartOptions.value && echartOptions.value.series)]
  },
  (v) => {
    if (v.every((t) => t)) {
      echartInstance.setOption(echartOptions.value)
    }
  }
)
</script>
<template>
  <div class="echarts-main">
    <div class="echarts-title">{{ pageTitle }}</div>
    <div class="echarts-container" ref="domRef"></div>
  </div>
</template>
<style lang="less" scoped>
.echarts-main {
  width: 100%;
  display: flex;
  flex-direction: column;

  .echarts-title {
    line-height: 40px;
    font-weight: bold;
    padding: 0 40px;
  }

  .echarts-container {
    flex: 1;
    width: 100%;
    min-height: 500px;
  }
}
</style>
